package com.example.tuomintest.config;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.example.tuomintest.log.Sensitive;
import com.example.tuomintest.log.SensitiveType;
import com.example.tuomintest.util.Decide;
import org.slf4j.helpers.MessageFormatter;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 敏感日志转换器
 * @author: 陈彦斌
 * @create: 2024-12-09 18:55
 */
public class SensitiveLogConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent event) {
        Object[] args = event.getArgumentArray();//对象的类型
        if (args == null || args.length == 0) {
            return event.getFormattedMessage();

        }
//        Object[] args = event.getArgumentArray();//对象的类型
//
//        if (args == null || args.length == 0 ) {
//            String message = event.getFormattedMessage();
//            System.out.println("args{}"+args);
//            System.out.println("message{}"+message);
//            return maskSensitiveData(message);
//
//        }
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if (arg != null) {
                args[i] = desensitize(arg);
            }
        }
        return MessageFormatter.arrayFormat(event.getMessage(), args).getMessage();
    }

    private Object desensitize(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            Class<?> clazz = obj.getClass();
            // 如果对象是集合类型
            if (obj instanceof List) {
                List<?> list = (List<?>) obj;
                List<Object> newList = new ArrayList<>();
                for (Object item : list) {
                    newList.add(desensitize(item)); // 递归处理列表中的每个对象
                }
                return newList;
            }
            // 如果对象是普通类型，直接返回
            if (isPrimitiveOrWrapper(clazz) || clazz == String.class) {
                //是String类型的
                if(clazz==String.class){
                    String str = obj.toString();
                    return  maskSensitiveData(str);
                }
                return obj;
            }
            // 创建新实例
            Object newObj = clazz.getDeclaredConstructor().newInstance();
            // 遍历字段
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object fieldValue = field.get(obj); // 获取原字段值
                if (fieldValue == null){
                    continue;
                }
                if (field.isAnnotationPresent(Sensitive.class)) {
                    // 处理标注为 @Sensitive 的字段
                    if (fieldValue instanceof String) {
                        Sensitive sensitive = field.getAnnotation(Sensitive.class);
                        SensitiveType type = sensitive.type();
                        field.set(newObj, applyDesensitization((String) fieldValue, type));
                    }else if (
                            fieldValue instanceof Integer
                                    || fieldValue instanceof Long
                                    || fieldValue instanceof BigDecimal
                                    || fieldValue instanceof Byte
                                    || fieldValue instanceof Short
                                    || fieldValue instanceof Float
                                    || fieldValue instanceof Double
                    ){
                        //数字直接脱敏
                        field.set(newObj, null);
                    }else if (fieldValue instanceof List) {
                        // 如果字段是 List 类型，递归处理其内部元素
                        List<?> list = (List<?>) fieldValue;
                        List<Object> newList = new ArrayList<>();
                        for (Object item : list) {
                            newList.add(desensitize(item));
                        }
                        field.set(newObj, newList);
                    } else {
                        // 对其他非字符串类型的字段，递归脱敏
                        field.set(newObj, desensitize(fieldValue));
                    }
                } else {
                    // 未标注 @Sensitive 的字段直接复制
                    field.set(newObj, fieldValue);
                }
            }
            return newObj; // 返回脱敏后的新对象
        } catch (Exception e) {
            e.printStackTrace();
            return obj; // 异常情况下返回原对象
        }
    }

    private String applyDesensitization(String value, SensitiveType type) {
        if (value==null || "".equals(value)){
            return "";
        }
        switch (type) {
            case DEFAULT:
                return value.replaceAll("^(.{3}).*$", "$1*****");
            case PHONE:
                if (value.length()<11||value.length()>11){
                    return value.replaceAll("^(.{5}).*$", "$1*****");
                }
                return value.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            case ID_CARD:
                if (value.length()<18){
                    return value.replaceAll("^(.{5}).*$", "$1*****");
                }
                return value.replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1**********$2");
            case EMAIL:
                if (!value.contains("@")){
                    return value.replaceAll("^(.{5}).*$", "$1*****");
                }
                return value.replaceAll("(?<=^.{3}).*(?=@)", "*****");
            case ADDRESS:
                if (value.length() <= 9) {
                    return value.replaceAll("(.)(.*)(..)", "$1*$2$3");
                }
                return value.replaceAll("(.{3}).*(.{3})", "$1*****$2");
            case USER_NAME:
                return value.replaceAll("(\\S)\\S(\\S*)", "$1*$2");
            default:
                return value;
        }
    }

    private boolean isPrimitiveOrWrapper(Class<?> clazz) {
        return clazz.isPrimitive() || clazz == Boolean.class || clazz == Integer.class ||
                clazz == Long.class || clazz == Double.class || clazz == Float.class ||
                clazz == Byte.class || clazz == Short.class || clazz == BigDecimal.class || clazz == Character.class;
    }

    private String maskSensitiveData(String message) {
        if (message == null || message.isEmpty()) {
            return message;
        }
        // 手机号脱敏: 13812345678 -> 138****5678->需要进一步判断这个参数是否是手机号
        if(Decide.isChinesePhoneNumber(message)){
            message = message.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            return message;
        }
        // 身份证号脱敏: 110105199003073335 -> 110105********3335
        message = message.replaceAll("(\\d{6})\\d{8}(\\w{4})", "$1********$2");

        // 银行卡号脱敏: 6225880137706868 -> 622588******6868
        message = message.replaceAll("(\\d{6})\\d{6}(\\d{4})", "$1******$2");

        //名字脱敏
        message = message.replaceAll("(\\S)\\S(\\S*)", "$1*$2");

        //地址脱敏
        if (message.length() <= 9) {
            message = message.replaceAll("(.)(.*)(..)", "$1*$2$3");
        }
        message = message.replaceAll("(.{3}).*(.{3})", "$1*****$2");
        //账号脱敏

        return message;
    }

}